package com.iotechn.unimall.core.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtils {
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public final static String DATE_INFO_PATTERN = "yyyy-MM-dd";


    public static String format(Date date) {
        return format(date, DATE_INFO_PATTERN);
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 判断时间格式 格式必须为“YYYY-MM-dd”
     * 2004-2-30 是无效的
     * 2003-2-29 是无效的
     *
     * @param sDate
     * @return
     */
    public static boolean isLegalDate(String sDate) {
        int legalLen = 10;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据开始时间和周期计算结束时间
     *
     * @param nowDate 当前时间
     * @param day     时长   1=7天/2=半个月/3=1个月/4=1季度/5=半年/6=1年
     */
    public static Date getDateInfo(Date nowDate, int day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowDate);
        switch (day) {
            case 1:
                cal.add(Calendar.DATE, 7);
                break; //可选
            case 2:
                //语句
                cal.add(Calendar.DATE, 15);
                break; //可选
            case 3:
                cal.add(Calendar.MONTH, 1);
                break; //可选
            case 4:
                //语句
                cal.add(Calendar.MONTH, 3);
                break; //可选
            case 5:
                //语句
                cal.add(Calendar.MONTH, 6);
                break; //可选
            case 6:
                //语句
                cal.add(Calendar.YEAR, 1);
                break; //可选
            //你可以有任意数量的case语句
            default: //可选
                //语句

        }

        System.out.println(sdf.format(cal.getTime()));
        return cal.getTime();
    }


    /**
     * 获取当前日期前30天的日期(用于返回30天内血糖和血压)
     */
    public static Map<String, String> getDayMap() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calc = Calendar.getInstance();
            Map<String, String> bloodMap = new HashMap<String, String>();
            for (int i = 1; i <= 30; i++) {
                calc.setTime(new Date());
                calc.add(calc.DATE, -i);
                Date minDate = calc.getTime();
                bloodMap.put(sdf.format(minDate), "0");
                System.out.println(sdf.format(minDate));
            }
            return bloodMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前日期前30天的日期(用于返回30天内血糖和血压)
     */
    public static Map<String, Integer> getDayMap1() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calc = Calendar.getInstance();
            Map<String, Integer> bloodMap = new LinkedHashMap<String, Integer>();
            for (int i = 30; i >= 1; i--) {
                calc.setTime(new Date());
                calc.add(calc.DATE, -i);
                Date minDate = calc.getTime();
                bloodMap.put(sdf.format(minDate), 0);
                System.out.println(sdf.format(minDate));
            }
            return bloodMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前时间的零点时间
     *
     * @param date
     * @return
     */
    public static Date getZeroDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        return zero;
    }

    /**
     * 获取 days 天的日期   正数 n天后  负数 n 天前
     *
     * @param date
     * @param days
     * @return
     */
    public static Date getBeforeSomeDaysDate(Date date, Integer days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + days);
        date = calendar.getTime();
        return date;
    }

    /**
     * 根剧格式转换时间 2 字符串
     *
     * @param format
     * @param date
     * @return
     */
    public static String dateToString(String format, Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateStr = formatter.format(date);
        return dateStr;
    }


    /**
     * 获取时间  的小时和分钟
     *
     * @param date
     * @return
     */
    public static String getDateMAndH(Date date) {
        if (date == null) {
            return "00:00";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);                    //放入Date类型数据
//		calendar.get(Calendar.YEAR);					//获取年份
//		calendar.get(Calendar.MONTH);					//获取月份
//		calendar.get(Calendar.DATE);					//获取日
//		calendar.get(Calendar.HOUR);					//时（12小时制）
//		calendar.get(Calendar.SECOND);					//秒
        String hour = calendar.get(Calendar.HOUR_OF_DAY) + "";//时（24小时制）
        String minute = calendar.get(Calendar.MINUTE) + "";//分
        if (minute.toString().length() < 2) {
            minute = "0" + minute;
        }
        return hour + ":" + minute;
    }

    /**
     * 日期转字符串
     *
     * @param strDate
     * @param formate
     * @return
     */
    public static Date getDateByStr(String strDate, String formate) throws ParseException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formate);//注意月份是MM
        date = simpleDateFormat.parse(strDate);
        return date;
    }


    /**
     * 根据时间获取星期
     *
     * @param date
     * @return
     */
    public static String getWeekByDate(Date date) {
        String[] weeks = {"日", "一", "二", "三", "四", "五", "六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }


    /**
     * 显示时间，如果与当前时间差别小于一天，则自动用**秒(分，小时)前，如果大于一天则用format规定的格式显示
     *
     * @param ctime  时间
     * @param format 格式 格式描述:例如:yyyy-MM-dd yyyy-MM-dd HH:mm:ss
     * @return
     * @author wxy
     */
    public static String showTime(Date ctime, String format) {
        //System.out.println("当前时间是："+new Timestamp(System.currentTimeMillis()));
        //System.out.println("发布时间是："+df.format(ctime).toString());
        String r = "";
        if (ctime == null) return r;
        if (format == null) format = "MM-dd HH:mm";

        long nowtimelong = System.currentTimeMillis();

        long ctimelong = ctime.getTime();
        long result = Math.abs(nowtimelong - ctimelong);

        if (result < 60000) {// 一分钟内
            long seconds = result / 1000;
            if (seconds == 0) {
                r = "刚刚";
            } else {
                r = seconds + "秒前";
            }
        } else if (result >= 60000 && result < 3600000) {// 一小时内
            long seconds = result / 60000;
            r = seconds + "分钟前";
        } else if (result >= 3600000 && result < 86400000) {// 一天内
            long seconds = result / 3600000;
            r = seconds + "小时前";
        } else if (result >= 86400000 && result < 1702967296) {// 三十天内
            long seconds = result / 86400000;
            r = seconds + "天前";
        } else {// 日期格式
            format = "MM-dd HH:mm";
            SimpleDateFormat df = new SimpleDateFormat(format);
            r = df.format(ctime).toString();
        }
        return r;
    }

    //类型(0:今天 1:昨天 2:本周 3.本月)
    //获取开始结束时间
    public static List<Date> getStartTimeAndEndTimeByType(Integer type) {
        Date startTime = null;
        Date endTime = null;
        List<Date> result = new LinkedList<>();
        type = (type == null) ? 0 : type;
        switch (type) {
            case 0://今日
            default:
                //当天开始时间
                Calendar todayStartTime = new GregorianCalendar();
                todayStartTime.set(Calendar.HOUR_OF_DAY, 0);
                todayStartTime.set(Calendar.MINUTE, 0);
                todayStartTime.set(Calendar.SECOND, 0);
                startTime = todayStartTime.getTime();
                //当天结束
                Calendar todayEndTime = new GregorianCalendar();
                todayEndTime.set(Calendar.HOUR_OF_DAY, 23);
                todayEndTime.set(Calendar.MINUTE, 59);
                todayEndTime.set(Calendar.SECOND, 59);
                endTime = todayEndTime.getTime();
                break;
            case 1://昨天
                //昨天开始时间
                Calendar yesterdayStartTime = new GregorianCalendar();
                yesterdayStartTime.set(Calendar.MILLISECOND, 0);
                yesterdayStartTime.set(Calendar.SECOND, 0);
                yesterdayStartTime.set(Calendar.MINUTE, 0);
                yesterdayStartTime.set(Calendar.HOUR_OF_DAY, 0);
                yesterdayStartTime.add(Calendar.DAY_OF_MONTH, -1);
                startTime = yesterdayStartTime.getTime();
                //昨天结束
                Calendar yesterdayEndTime = new GregorianCalendar();
                yesterdayEndTime.set(Calendar.HOUR_OF_DAY, 23);
                yesterdayEndTime.set(Calendar.MINUTE, 59);
                yesterdayEndTime.set(Calendar.SECOND, 59);
                yesterdayEndTime.add(Calendar.DAY_OF_MONTH, -1);
                endTime = yesterdayEndTime.getTime();
                break;
            case 2://本周
                //本周开始时间
                Calendar currentWeekStartTime = Calendar.getInstance();
                currentWeekStartTime.set(currentWeekStartTime.get(Calendar.YEAR), currentWeekStartTime.get(Calendar.MONDAY), currentWeekStartTime.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
//                if (currentWeekStartTime.get(Calendar.DAY_OF_WEEK) == 1) {
//                    currentWeekStartTime.add(Calendar.DAY_OF_WEEK, -6);
//                }
                int dayWeek = currentWeekStartTime.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
                if (1 == dayWeek) {
                    currentWeekStartTime.add(Calendar.DAY_OF_MONTH, -1);
                }
                currentWeekStartTime.setFirstDayOfWeek(Calendar.MONDAY);
                int day = currentWeekStartTime.get(Calendar.DAY_OF_WEEK);
                currentWeekStartTime.add(Calendar.DATE, currentWeekStartTime.getFirstDayOfWeek() - day);
                startTime = currentWeekStartTime.getTime();
                //本周结束时间
                Calendar currentWeekEndTime = Calendar.getInstance();
                currentWeekEndTime.setFirstDayOfWeek(Calendar.MONDAY);
                currentWeekEndTime.set(Calendar.HOUR_OF_DAY, 23);
                currentWeekEndTime.set(Calendar.MINUTE, 59);
                currentWeekEndTime.set(Calendar.SECOND, 59);
                currentWeekEndTime.set(Calendar.DAY_OF_WEEK, currentWeekEndTime.getFirstDayOfWeek() + 6); // Sunday
                endTime = currentWeekEndTime.getTime();
                break;
            case 3://本月
                //本月开始时间
                Calendar currentMonthStartTime = Calendar.getInstance();
                currentMonthStartTime.add(Calendar.YEAR, 0);
                currentMonthStartTime.add(Calendar.MONTH, 0);
                currentMonthStartTime.set(Calendar.DAY_OF_MONTH, 1);
                currentMonthStartTime.set(Calendar.HOUR_OF_DAY, 0);
                currentMonthStartTime.set(Calendar.MINUTE, 0);
                currentMonthStartTime.set(Calendar.SECOND, 0);
                startTime = currentMonthStartTime.getTime();
                //本月结束时间
                endTime = new Date();
                break;
            case 4://上周
                //上周开始时间
                Calendar lastWeekStartTime = Calendar.getInstance();
                lastWeekStartTime.set(lastWeekStartTime.get(Calendar.YEAR), lastWeekStartTime.get(Calendar.MONDAY), lastWeekStartTime.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
//                if (currentWeekStartTime.get(Calendar.DAY_OF_WEEK) == 1) {
//                    currentWeekStartTime.add(Calendar.DAY_OF_WEEK, -6);
//                }
                int dayWeekLast = lastWeekStartTime.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
                if (1 == dayWeekLast) {
                    lastWeekStartTime.add(Calendar.DAY_OF_MONTH, -1);
                }
                lastWeekStartTime.setFirstDayOfWeek(Calendar.MONDAY);
                int dayLast = lastWeekStartTime.get(Calendar.DAY_OF_WEEK);
                lastWeekStartTime.add(Calendar.DATE, lastWeekStartTime.getFirstDayOfWeek() - dayLast - 7);
                startTime = lastWeekStartTime.getTime();
                //本周结束时间
                Calendar lastWeekEndTime = Calendar.getInstance();

                lastWeekEndTime.set(Calendar.HOUR_OF_DAY, 23);
                lastWeekEndTime.set(Calendar.MINUTE, 59);
                lastWeekEndTime.set(Calendar.SECOND, 59);
                int dayLastEnd = lastWeekStartTime.get(Calendar.DAY_OF_WEEK);
                lastWeekEndTime.add(Calendar.DATE, lastWeekEndTime.getFirstDayOfWeek() - dayLastEnd);
                endTime = lastWeekEndTime.getTime();
                break;
            case 5://上月
                //上月开始时间
                Calendar lastMonthStartTime = Calendar.getInstance();
                lastMonthStartTime.add(Calendar.YEAR, 0);
                lastMonthStartTime.add(Calendar.MONTH, -1);
                lastMonthStartTime.set(Calendar.DAY_OF_MONTH, 1);
                lastMonthStartTime.set(Calendar.HOUR_OF_DAY, 0);
                lastMonthStartTime.set(Calendar.MINUTE, 0);
                lastMonthStartTime.set(Calendar.SECOND, 0);
                startTime = lastMonthStartTime.getTime();
                //上月结束时间
                Calendar lastMonthEndTime = Calendar.getInstance();
                lastMonthEndTime.add(Calendar.YEAR, 0);
                lastMonthEndTime.add(Calendar.MONTH, -1);
                lastMonthEndTime.set(Calendar.DAY_OF_MONTH, lastMonthEndTime.getActualMaximum(Calendar.DAY_OF_MONTH));
                lastMonthEndTime.set(Calendar.HOUR_OF_DAY, 23);
                lastMonthEndTime.set(Calendar.MINUTE, 59);
                lastMonthEndTime.set(Calendar.SECOND, 59);
                endTime = lastMonthEndTime.getTime();
                break;
        }
        if (startTime != null && endTime != null) {
            result.add(startTime);
            result.add(endTime);
        }
        return result;
    }


    //获取时间
    public static List<String> getEveryDays(Date startTime, Date endTime) {
        List<String> days = new LinkedList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            while (calendar.getTime().before(endTime)) {
                days.add(dateFormat.format(calendar.getTime()));
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                if (calendar.getTime().after(new Date())) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     *  获取当前时间+毫秒值后的Date
     * @param now
     * @param millisec
     * @return
     */
    public static Date getSecAfterTime(Date now,Long millisec){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MILLISECOND,millisec.intValue());
        return calendar.getTime();
    }

}
